import ij.ImagePlus;
import ij.plugin.filter.PlugInFilter;
import ij.process.ImageProcessor;


public class Rayleigh_ implements PlugInFilter {

	private final static double gamma = 255*0.5;
	private final static double k = 2;
	
	private int[] getTransformationArray() {
		int[] T = new int[256];
		for (int i = T.length-1; i >=0 ; i--) {
			T[i] = (int) ((1 - Math.pow(Math.E, -Math.pow(i/gamma, k)))*255);
			if (T[i] < 0) {
				T[i] = 0;
			}
		}
		return T;
	}
	
	public void run(ImageProcessor ipO) {
		if (ipO == null) {
			return;
		}
		int[] t = getTransformationArray();
		final int[] pO = (int[]) ipO.getPixels();
		final int width = ipO.getWidth();
		final int height = ipO.getHeight();
		for (int y = height-1; y >= 0; y--) {
			final int offset = y * width;
			for (int x = width-1; x >= 0; x--) {
				final int i = offset + x;
				final int pixelValue = pO[i];
				int c1Value = ( pixelValue & 0xFF    )       ;
				int c2Value = ((pixelValue & 0xFF00  ) >>> 8) ;
				int c3Value = ((pixelValue & 0xFF0000) >>> 16);
				pO[i] = (t[c3Value] << 16) | (t[c2Value] << 8) | t[c1Value];
			}
		}
	}

	public int setup(String arg, ImagePlus ip) {
		return DOES_RGB;
	}

}
